package com.example.sunflowers.ui.viewpage

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import cn.trans88.taxiappkotlin.ext.logd
import cn.trans88.taxiappkotlin.ext.loge
import com.example.sunflowers.R
import com.example.sunflowers.adapters.PlantAdapter
import com.example.sunflowers.databinding.FragmentPlantListBinding
import com.example.sunflowers.viewmodels.PlantListViewModel
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class PlantListFragment : Fragment() {

    private val viewModel:PlantListViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        "PlantListFragment onCreate".logd()
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        "PlantListFragment onCreateView".logd()
        val binding = FragmentPlantListBinding.inflate(inflater,container,false)
        context ?: return binding.root

        val adapter = PlantAdapter()
        binding.plantList.adapter = adapter
        subscribe(adapter)
        setHasOptionsMenu(true)
        return binding.root
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.menu_plant_list,menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when(item.itemId){
            R.id.filter_zone -> {
                updateData()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    private fun subscribe(adapter: PlantAdapter){
        viewModel.plants.observe(viewLifecycleOwner){ plants ->
            "plants.size:${plants.size}".loge()
            for (plant in plants) {
                "plant.id:${plant.plantId}".loge()
            }
            adapter.submitList(plants)
        }
    }

    private fun updateData(){
        with(viewModel) {
            if (isFiltered()){
                clearGrowZoneNumber()
            } else {
                setGrowZoneNumber(9)
            }
        }
    }

    override fun onResume() {
        super.onResume()
        "plantListFragment onResume".logd()
    }
}